package api

import (
	"context"
	"strings"
	"time"

	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/backend/model"
	"mall/service/backend/rpc/internal/svc"
	"mall/service/backend/rpc/internal/utils/errorhandler"
	"mall/service/backend/rpc/types/backend"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateApiLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateApiLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateApiLogic {
	return &UpdateApiLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateApiLogic) UpdateApi(in *backend.ApiInfo) (*backend.BaseResp, error) {
	if len(in.Ids) > 0 {
		tx, err := l.svcCtx.DB.BeginTx(l.ctx, nil)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		now := time.Now()
		for _, id := range in.Ids {
			if id > 0 {
				api, err := l.svcCtx.SysApi.FindOneNoCache(l.ctx, tx, id)
				if err != nil {
					tx.Rollback()
					return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
				}

				if in.Status != nil {
					api.Status = uint8(*in.Status)
				}
				api.UpdatedAt = now
				err = l.svcCtx.SysApi.Update(l.ctx, tx, api)
				if err != nil {
					tx.Rollback()
					return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
				}
			}
		}

		tx.Commit()

		return &backend.BaseResp{
			Msg: i18n.UpdateSuccess,
		}, nil
	}

	if in.Id == nil || *in.Id == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	id := *in.Id

	api, err := l.svcCtx.SysApi.FindOneNoCache(l.ctx, nil, id)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	if in.Path != nil {
		api.Path = strings.TrimSpace(*in.Path)

		if len(api.Path) == 0 {
			return nil, errorx.NewInvalidArgumentError("api.pathRequired")
		}

		filterMap := make(map[string]map[string][]any)
		filterMap[model.SysAPIColumns.Path] = map[string][]any{
			"equalTo": []any{api.Path},
		}
		list, _, err := l.svcCtx.SysApi.GetList(l.ctx, model.M{
			"pageSize": uint64(2),
			"select":   ",",
		}, -1, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		count := len(list)
		if count > 1 {
			return nil, errorx.NewAlreadyExistsError("api.pathAlreadyExists")
		}

		if count == 1 && list[0].ID != id {
			return nil, errorx.NewAlreadyExistsError("api.pathAlreadyExists")
		}
	}
	if in.Description != nil {
		api.Description = strings.TrimSpace(*in.Description)
	}
	if in.Group != nil {
		api.APIGroup = strings.TrimSpace(*in.Group)
	}
	if in.Method != nil {
		api.Method = strings.ToUpper(strings.TrimSpace(*in.Method))
	}
	if in.Required != nil {
		api.IsRequired = uint8(*in.Required)
	}
	if in.Status != nil {
		api.Status = uint8(*in.Status)
	}
	api.UpdatedAt = time.Now()
	err = l.svcCtx.SysApi.Update(l.ctx, nil, api)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	return &backend.BaseResp{
		Msg: i18n.UpdateSuccess,
	}, nil
}
